<template>
  <div id="userLayout">
    <div class="loginTitle">
      <img src="@/assets/common/logo.png" alt="" />
      <div class="loginText">养老服务管理系统</div>
    </div>
    <div class="login_panel">
      <div class="login_panel_form">
        <div class="login_panel_form_title">
          <p class="login_panel_form_title_p">用户登陆</p>
        </div>
        <el-form
          ref="loginForm"
          :model="loginFormData"
          :rules="rules"
          :validate-on-rule-change="false"
          @keyup.enter="submitForm"
        >
          <el-form-item prop="username">
            <el-input
              v-model.trim="loginFormData.username"
              placeholder="请输入用户名"
            >
              <template #suffix>
                <span class="input-icon">
                  <el-icon :size="20">
                    <user />
                  </el-icon>
                </span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model.trim="loginFormData.password"
              :type="lock === 'lock' ? 'password' : 'text'"
              placeholder="请输入密码"
            >
              <template #suffix>
                <span class="input-icon password">
                  <el-icon :size="20">
                    <component :is="lock" @click="changeLock" />
                  </el-icon>
                </span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="captcha">
            <div class="vPicBox">
              <el-input
                v-model.trim="loginFormData.captcha"
                placeholder="请输入验证码"
                style="width: 60%"
              />
              <div class="vPic">
                <img
                  v-if="picPath"
                  :src="picPath"
                  alt="请输入验证码"
                  @click="getCaptchaCode()"
                />
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              size="large"
              :loading="btnLoading"
              v-prevent-repeat-click
              style="width: 100%; height: 34px !important; margin-left: 0%"
              @click="submitForm"
            >
              登 录
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- <div class="login_panel_foot">
      <div class="copyright">养老服务管理系统</div>
    </div> -->

    <pub-dialog
      v-if="dialogFormVisibleUpdatePWD"
      title="修改密码"
      v-model:visible="dialogFormVisibleUpdatePWD"
      width="600px"
      :showClose="pwdInfo.required"
      @close="close"
    >
      <updatepwd
        ref="ruleFormRef"
        :pwdInfo="pwdInfo"
        @close="close"
        @submitForm="submitFormPW"
      />
    </pub-dialog>
  </div>
</template>

<script>
export default {
  name: 'Login'
}
</script>

<script setup>
import { updatepwdSubmit,getSysparamFileServer } from '@/api/system'
import { sessionMemory } from '@/utils/sessionMemory'
import updatepwd from './updatepwd.vue'
import { getCaptcha, getUserCheckPwd } from '@/api/api'
import { onBeforeMount, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/pinia/modules/user'
import { Sm4encrypt } from '@/utils/encryption.js'
const router = useRouter()
// 验证函数
const checkUsername = (rule, value, callback) => {
  if (value.length === 0) {
    return callback(new Error('请输入正确的用户名'))
  } else {
    callback()
  }
}
const checkPassword = (rule, value, callback) => {
  if (value.length < 6) {
    return callback(new Error('请输入正确的密码'))
  } else {
    callback()
  }
}

const dialogFormVisibleUpdatePWD = ref(false)
const pwdInfo = reactive({
  name: '',
  msg: '',
  required: false
})

// 登录相关操作
const isTopMenus = ref(window.sessionStorage.getItem('isTopMenus') || 1)
const loginForm = ref(null)
const picPath = ref('')
const lock = ref('lock')
const btnLoading = ref(false)
const changeLock = () => {
  lock.value = lock.value === 'lock' ? 'unlock' : 'lock'
}
const captchaKey = ref('')
const getCaptchaCode = async () => {
  let res = await getCaptcha()
  if (res.succeed) {
    ;(picPath.value = res.data.captchaImageBase64),
      (captchaKey.value = res.data.captchaKey)
  }
}
const userStore = useUserStore()
const state = reactive({
  result: {}
})
const loginFormData = reactive({
  username: 'admin2',
  password: 'P6Uw5#!t',
  captcha: ''
})
const rules = reactive({
  username: [{ validator: checkUsername, trigger: 'blur' }],
  password: [{ validator: checkPassword, trigger: 'blur' }],
  getCaptcha: [
    {
      message: '验证码格式不正确',
      trigger: 'blur'
    }
  ]
})

const getCheckPwd = async result => {
  const res = await getUserCheckPwd()
  if (res.succeed && res.status === 200) {
    // 判断是否显示顶部菜单
    if (result.data.user.enterIndex == 1) {
      // 有顶部菜单
      sessionMemory.setItem('isTopMenus', 1)
      isTopMenus.value = 1
      await userStore.getDefaultMenu(result.asyncRouters.leftRoutes)
    } else {
      // 无顶部菜单
      sessionMemory.setItem('isTopMenus', 2)
      isTopMenus.value = 2
      await userStore.getDefaultMenu(result.asyncRouters.allRoutes)
    }
  } else if (res.status === 1001 || res.status === 1002) {
    pwdInfo.required = true
    pwdInfo.msg = res.msg
    dialogFormVisibleUpdatePWD.value = true
  } else if (res.status === 1003 || res.status === 1004) {
    pwdInfo.required = false
    pwdInfo.msg = res.msg
    dialogFormVisibleUpdatePWD.value = true
  }
}

const login = async () => {
  pwdInfo.name = loginFormData.username
  let params = {}
  params.username = loginFormData.username
  params.password = Sm4encrypt(loginFormData.password)
  params.captchaKey = captchaKey.value
  params.captcha = loginFormData.captcha
  return await userStore.LoginIn(params)
}
const submitForm = () => {
  loginForm.value.validate(async v => {
    if (v) {
      btnLoading.value = true
      const result = await login()
      state.result = result
      if (result) {
        await getCheckPwd(result)
      } else {
        getCaptchaCode()
      }
      btnLoading.value = false
    }
  })
}

const close = async () => {
  if (state.result.data.user.enterIndex == 1) {
    // 有顶部菜单
    sessionMemory.setItem('isTopMenus', 1)
    isTopMenus.value = 1
    await userStore.getDefaultMenu(state.result.asyncRouters.leftRoutes)
  } else {
    // 无顶部菜单
    sessionMemory.setItem('isTopMenus', 2)
    isTopMenus.value = 2
    await userStore.getDefaultMenu(state.result.asyncRouters.allRoutes)
  }
  dialogFormVisibleUpdatePWD.value = false
}

// 提交修改密码
const submitFormPW = data => {
  const updateDate = {
    originalPassword: '',
    newPassword: ''
  }
  updateDate.originalPassword = Sm4encrypt(data.originalPassword)
  updateDate.newPassword = Sm4encrypt(data.newPassword)
  updatepwdSubmit(updateDate)
    .then(result => {
      if (result.succeed) {
        ElMessage.success(result.msg)
        userStore.LoginOut()
        dialogFormVisibleUpdatePWD.value = false
        ruleFormRef.value.btnLoading.value = false
      } else {
        ElMessage.error(result.msg)
      }
    })
    .catch(() => {})
}


// 获取验证码
getCaptchaCode()

</script>

<style lang="scss" scoped>
@import '@/style/newLogin.scss';
:deep(.el-input__wrapper) {
  height: 34px !important;
}
// .login_panel_form :deep(.el-button) {
//  height: 34px!important;
// }
</style>
